<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务管理系统</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .app-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .el-date-editor {
            width: 100%;
        }
        .status-tag {
            margin-left: 10px;
        }
        .action-buttons .el-button {
            padding: 5px;
        }
        .search-form {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <div class="header">
        <h2>任务管理系统</h2>
        <el-button
                type="primary"
                icon="el-icon-plus"
                size="medium"
                @click="showDialog('add')">
            新增任务
        </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" class="search-form" size="small" inline>
        <el-form-item label="项目ID">
            <el-input
                    v-model="queryParams.projectId"
                    placeholder="请输入项目ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="任务名称">
            <el-input
                    v-model="queryParams.name"
                    placeholder="请输入任务名称"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="状态">
            <el-select
                    v-model="queryParams.status"
                    placeholder="请选择状态"
                    clearable>
                <el-option label="未开始" value="0"></el-option>
                <el-option label="进行中" value="1"></el-option>
                <el-option label="已完成" value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getTasks">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>

    <!-- 任务列表表格 -->
    <el-table
            :data="taskList"
            style="width: 100%"
            v-loading="loading"
            border
            stripe>
        <el-table-column
                prop="taskId"
                label="任务ID"
                width="100">
        </el-table-column>
        <el-table-column
                prop="projectId"
                label="项目ID"
                width="100">
        </el-table-column>
        <el-table-column
                prop="name"
                label="任务名称">
        </el-table-column>
        <el-table-column
                prop="description"
                label="任务描述">
        </el-table-column>
        <el-table-column
                label="开始日期"
                width="120">
            <template slot-scope="scope">
                {{ formatDate(scope.row.startDate) }}
            </template>
        </el-table-column>
        <el-table-column
                label="结束日期"
                width="120">
            <template slot-scope="scope">
                {{ formatDate(scope.row.endDate) }}
            </template>
        </el-table-column>
        <el-table-column
                label="状态"
                width="100">
            <template slot-scope="scope">
                <el-tag
                        :type="getStatusType(scope.row.status)"
                        size="small"
                        class="status-tag">
                    {{ getStatusText(scope.row.status) }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column
                label="操作"
                width="180"
                class-name="action-buttons">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="showDialog('edit', scope.row)">
                    编辑
                </el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 任务对话框（新增/编辑） -->
    <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="500px"
            :close-on-click-modal="false">
        <el-form
                :model="formData"
                :rules="rules"
                ref="taskForm"
                label-width="100px">
            <el-form-item
                    label="项目ID："
                    prop="projectId">
                <el-input
                        v-model="formData.projectId"
                        placeholder="请输入项目ID"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="任务名称："
                    prop="name">
                <el-input
                        v-model="formData.name"
                        placeholder="请输入任务名称"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="任务描述："
                    prop="description">
                <el-input
                        v-model="formData.description"
                        type="textarea"
                        placeholder="请输入任务描述">
                </el-input>
            </el-form-item>
            <el-form-item
                    label="开始日期："
                    prop="startDate">
                <el-date-picker
                        v-model="formData.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择开始日期"
                        :picker-options="startDateOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item
                    label="结束日期："
                    prop="endDate">
                <el-date-picker
                        v-model="formData.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择结束日期"
                        :picker-options="endDateOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item
                    label="任务状态："
                    prop="status">
                <el-select
                        v-model="formData.status"
                        placeholder="请选择状态"
                        style="width:100%">
                    <el-option label="未开始" value="not_started"></el-option>
                    <el-option label="进行中" value="in_progress"></el-option>
                    <el-option label="已完成" value="completed"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="submitting">
                {{ dialogType === 'add' ? '新增' : '保存' }}
            </el-button>
        </div>
    </el-dialog>
</div>

<!-- 引入Vue和Element UI -->
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../api/login.js"></script>
<script src="https://unpkg.com/dayjs@1.10.7/dayjs.min.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            // 验证结束日期不能早于开始日期
            const validateEndDate = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请选择结束日期'));
                } else if (this.formData.startDate && new Date(value) < new Date(this.formData.startDate)) {
                    callback(new Error('结束日期不能早于开始日期'));
                } else {
                    callback();
                }
            };

            return {
                loading: false,          // 表格加载状态
                submitting: false,       // 提交按钮加载状态
                dialogVisible: false,    // 对话框显示状态
                dialogType: 'add',       // 对话框类型：add/edit
                dialogTitle: '新增任务', // 对话框标题
                taskList: [],           // 任务列表数据
                total: 0,               // 总条数
                queryParams: {           // 查询参数
                    pageNum: 1,
                    pageSize: 10,
                    projectId: '',
                    name: '',
                    status: ''
                },
                formData: {              // 表单数据
                    taskId: '',
                    projectId: '',
                    name: '',
                    description: '',
                    startDate: '',
                    endDate: '',
                    status: 'in_progress'          // 默认状态为"未开始"
                },
                rules: {                 // 表单验证规则
                    projectId: [
                        { required: true, message: '请输入项目ID', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入任务名称', trigger: 'blur' },
                        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
                    ],
                    startDate: [
                        { required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    endDate: [
                        { required: true, validator: validateEndDate, trigger: 'change' }
                    ],
                    status: [
                        { required: true, message: '请选择任务状态', trigger: 'change' }
                    ]
                },
                // 开始日期选择限制（不能选择今天之前的日期）
                startDateOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
                    }
                },
                // 结束日期选择限制（不能选择开始日期之前的日期）
                endDateOptions: {
                    disabledDate: (time) => {
                        if (this.formData.startDate) {
                            return time.getTime() < new Date(this.formData.startDate).getTime() - 8.64e7;
                        }
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                }
            };
        },
        created() {
            // 组件创建时加载任务列表
            this.getTasks();
        },
        methods: {
            // 获取任务列表
            getTasks() {
                this.loading = true;
                // 转换查询参数为后端期望的格式
                const params = {
                    pageNum: this.queryParams.pageNum,
                    pageSize: this.queryParams.pageSize,
                    projectId: this.queryParams.projectId || null,
                    name: this.queryParams.name || null,
                    status: this.queryParams.status || null
                };

                axios.get('/task', { params })
                    .then(response => {
                        // 确保正确处理响应数据
                        if (response.data && response.data.rows) {
                            this.taskList = response.data.rows;
                            this.total = response.data.total || 0;
                        } else {
                            this.taskList = [];
                            this.total = 0;
                        }
                    })
                    .catch(error => {
                        console.error('获取任务列表失败:', error);
                        this.$message.error('获取任务列表失败: ' + (error.response?.data?.message || error.message));
                        this.taskList = [];
                        this.total = 0;
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 显示对话框
            showDialog(type, row) {
                this.dialogType = type;
                this.dialogTitle = type === 'add' ? '新增任务' : '编辑任务';

                if (type === 'add') {
                    // 新增模式，重置表单
                    this.formData = {
                        taskId: '',
                        projectId: '',
                        name: '',
                        description: '',
                        startDate: '',
                        endDate: '',
                        status: 'in_progress'
                    };
                } else {
                    // 编辑模式，填充表单数据
                    this.formData = {
                        taskId: row.taskId,
                        projectId: row.projectId,
                        name: row.name,
                        description: row.description,
                        startDate: row.startDate,
                        endDate: row.endDate,
                        status: row.status
                    };
                }

                this.dialogVisible = true;

                // 清除验证状态
                this.$nextTick(() => {
                    if (this.$refs.taskForm) {
                        this.$refs.taskForm.clearValidate();
                    }
                });
            },

            // 提交表单（新增/编辑）
            submitForm() {
                this.$refs.taskForm.validate(valid => {
                    if (valid) {
                        this.submitting = true;

                        const isAdd = this.dialogType === 'add';
                        const request = isAdd
                            ? axios.post('/task', this.formData)
                            : axios.put('/task', this.formData);

                        request.then(response => {
                            this.$message.success(isAdd ? '新增任务成功' : '更新任务成功');
                            this.dialogVisible = false;
                            this.getTasks(); // 刷新列表
                        })
                            .catch(error => {
                                this.$message.error((isAdd ? '新增' : '更新') + '任务失败: ' +
                                    (error.response?.data?.message || error.message));
                            })
                            .finally(() => {
                                this.submitting = false;
                            });
                    }
                });
            },

            // 删除任务
            handleDelete(row) {
                this.$confirm('确定要删除该任务吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    axios.delete(`/task/${row.taskId}`)
                        .then(response => {
                            this.$message.success('删除任务成功');
                            this.getTasks(); // 刷新列表
                        })
                        .catch(error => {
                            this.$message.error('删除任务失败: ' +
                                (error.response?.data?.message || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }).catch(() => {
                    // 用户取消删除
                });
            },

            // 格式化日期显示
            // 格式化日期显示
            formatDate(date) {
                if (!date) return '-';  // 如果日期为空，返回 -
                return dayjs(date).format('YYYY-MM-DD HH:mm:ss');  // 使用 dayjs 格式化日期
            }
            ,

            // 获取状态显示文本
            getStatusText(status) {
                const statusMap = { 'not_started': '未开始', 'in_progress': '进行中', 'completed': '已完成'};
                return statusMap[status] || '未知';
            },

            // 获取状态标签类型
            getStatusType(status) {
                const typeMap = { 'not_started': 'info', 'in_progress': 'primary', 'completed': 'success' };
                return typeMap[status] || 'info';
            },

            // 分页大小改变
            handleSizeChange(val) {
                this.queryParams.pageSize = val;
                this.getTasks();
            },

            // 当前页改变
            handleCurrentChange(val) {
                this.queryParams.pageNum = val;
                this.getTasks();
            },

            // 重置查询
            resetQuery() {
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    projectId: '',
                    name: '',
                    status: ''
                };
                this.getTasks();
            }
        }
    });
</script>
</body>
</html>